﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import urllib2
import recipe
from lib.parsing import *
from google.appengine.api import search

INDEX_NAME = "recipes_index"

def index_all_gotovim_doma_recipes():
  DATA = "data/gotovim_doma_hosted.json"
  
  for line in open(os.path.join(os.getcwd(), DATA)):
    r = recipe.Recipe.from_json(json.loads(line))
    try:
      search.Index(name=INDEX_NAME).put(r.as_search_doc())
    except search.Error:
      logging.exception('Put failed')


def delete_all_in_index(index_name = INDEX_NAME):
  """Delete all the docs in the given index."""
  doc_index = search.Index(name=index_name)

  while True:
    # Get a list of documents populating only the doc_id field and extract the ids.
    document_ids = [document.doc_id
            for document in doc_index.get_range(ids_only=True)]
    if not document_ids:
      break
    # Delete the documents for the given ids from the Index.
    doc_index.delete(document_ids)